<?php
if(!defined('BASEPATH')) exit('Akses langsung tidak diperkenankan');

class Profil extends CI_Controller {
    var $_admin_view = '';

    function __construct() {
        parent::__construct();
        $this->load->model('model_admin', 'madmin');
        $this->load->model('model_agen', 'magen');
        $this->load->helper(array('url','form'));
        $this->load->library(array('session','table'));
        $this->config->load('artyproperty');
        $this->_admin_view = $this->config->item('admin_view').'wrapper';
    }

    function index() {
        //cek session
        $islogin = $this->session->userdata('isLogin');
        $user = '';
        if ($islogin) {
            $user = $this->session->userdata('username');
            $level = $this->session->userdata('level');
        } else {
            redirect(site_url(),'location');
        }

        $data = array('daftar_user' => $this->magen->get_agen_admin(),
            'page_title' => 'Kelola Agen',
            'page_content' => 'daftar_user',
            'isLogin' => $islogin, 'level_user' => $level,
            'user' => $user);
        $this->load->view($this->_admin_view,$data);
    }

    function form_tambah_user() {
        //cek session
        $islogin = $this->session->userdata('isLogin');
        $user = '';
        if ($islogin) {
            $user = $this->session->userdata('username');
            $level = $this->session->userdata('level');
        }else {
            redirect(site_url(),'location');
        }

        $data = array('isUpdate'=>FALSE,
            'page_title' => 'Tambah Agen',
            'page_content' => 'tambah_user',
            'nama' =>'', 'username' =>'', 'email' =>'','password' => '',
            'nama_depan'=>'','nama_belakang'=>'',
            'isLogin' => $islogin, 'level_user' => $level,
            'user' => $user);
        $this->load->view($this->_admin_view,$data);
    }

    /**
     * fungsi untuk mendaftarkan data user ke database sistem
     */
    public function tambah_user() {
        //ambil dari method POST
        $reg['nama_depan'] = $this->input->post('nama_depan');
        $reg['nama_belakang'] = $this->input->post('nama_belakang');
        $reg['username'] = $this->input->post("username");
        $reg['email'] = $this->input->post('email');
        $reg['password'] = md5($this->input->post("password"));
        $reg['level'] = 2;  //default level di set 1
        $reg['alamat_id'] = 3;  //ini dummy default alamatnya di 3 (nanti harus berdasar input ya)
        $reg['perusahaan_id'] = 2; 
        $reg['bahasa_id'] = 1; 
        $reg['spesialisasi_prop_id'] = 1; 

        //cek validasi masukkan
        if ($this->validation()) {
            $this->db->trans_begin();
            $this->db->insert('user', $reg);
            if ($this->db->trans_status() == FALSE) {
                $this->db->trans_rollback();
            } else {
                $this->db->trans_commit();
                redirect('admin/profil','location');
//                $this->session->set_userdata('isLogin', true);
//                $this->session->set_userdata('username', $reg['username']);
//
//                $data = array('page_content' => 'daftar_user',
//                            'page_title' => 'registrasi',
//                            'level_user' => $reg['level'],
//                            'daftar_user' => $this->magen->get_agen_admin(),
//                            'user' => $this->session->userdata('username'),
//                            'isLogin' => TRUE,
//                            'note'=>'');
            }
        } else {
            $data = array('page_content' => 'tambah_user',
                            'page_title' => 'Error',
                            'level_user' => $this->session->userdata('level'), 
                            'user' => $this->session->userdata('username'),
                            'isLogin' => TRUE,'login'=>'',
                            'nama' => '', 'username' => '', 'email' =>'',
                            'nama_depan'=>'','nama_belakang'=>'',
                            'password' => '','isUpdate' => FALSE,
                            'note'=>'');
        }
        
        $this->load->view($this->_admin_view, $data);  //tampilkan datanya
    }

    /**
     * fungsi untuk mengecek validasi masukkan user saat registrasi
     * @return <type>
     */
    public function validation($str=''){
        $this->load->library('form_validation');

        $this->valid = $this->form_validation;

        //konfigurasi aturan2 masukkan valid
        $this->valid->set_rules('nama_depan','nama_depan','trim|required|min_length[4]|max_length[20]');
        if($str!='update'){
            $this->valid->set_rules('username','username','trim|required|min_length[4]|max_length[20]|callback_spare_username');
        } else {
            $this->valid->set_rules('username','username','trim|required|min_length[4]|max_length[20]');
        }
        $this->valid->set_rules('email','email','trim|required|valid_email');
        // $this->valid->set_rules('password','password','required|min_length[6]|matches[pass_conf]');
        // $this->valid->set_rules('pass_conf','password confirmation','trim|required');
        //end konfigurasi

        return ($this->form_validation->run()==FALSE) ? FALSE : TRUE;
    }

    function form_update_user(){
        //cek session
        $islogin = $this->session->userdata('isLogin');
        $user = '';
        if ($islogin) {
            $user = $this->session->userdata('username');
            $level = $this->session->userdata('level');
        }else {
            redirect(site_url(),'location');
        }
        $user_id = $this->uri->segment(4);
        $query = $this->madmin->get_user(array('user_id'=>$user_id));
        $udata = $query->row();
        $data = array(
            'isUpdate'=>TRUE,
            'page_title' => 'Edit Profil',
            'page_content' => 'tambah_user', 'nama_belakang' => $udata->nama_belakang,
            'nama_depan' => $udata->nama_depan, 'email' => $udata->email,'password'=> $udata->password,
            'username' => $udata->username, 'user_id'=>$udata->user_id,
            'isLogin' => $islogin, 'level_user' => $level,
            'user' => $user);
        $this->load->view($this->_admin_view,$data);
    }

    public function update_user($user_id = '') {
        //cek session
        $islogin = $this->session->userdata('isLogin');
        $user = '';
        $uid ='';
        if ($islogin) {
            $user = $this->session->userdata('username');
            $level = $this->session->userdata('level');
            $uid = $this->session->userdata('user_id');
        }else {
            redirect(site_url(),'location');
        }
        
        //ambil dari method POST
        $reg['nama_depan'] = $this->input->post('nama_depan');
        $reg['nama_belakang'] = $this->input->post('nama_belakang');
        $reg['username'] = $this->input->post("username");
        $reg['email'] = $this->input->post('email');
        $reg['password'] = md5($this->input->post("password"));
        $reg['level'] = 1;  //default level di set 1
        $reg['alamat_id'] = 3;  //ini dummy default alamatnya di 3 (nanti harus berdasar input ya)
        $check = '';

        //cek validasi masukkan
        if ($this->validation('update')) {
            if($user_id == $uid){
                $this->session->unset_userdata('username');
                $this->session->set_userdata('username',$reg['username']);
            }
            $this->db->trans_begin();
            $this->db->where('user_id', $user_id);
            $this->db->update('user',$reg);
            if ($this->db->trans_status() == FALSE) {
                $this->db->trans_rollback();
            } else {                
                $this->db->trans_commit();
                if($user_id==$this->session->userdata('user_id')){
                    redirect('admin/dashboard','location');
                }
                redirect('admin/profil','location');
//                $this->session->set_userdata('isLogin', true);
//                $this->session->set_userdata('username', $reg['username']);
//
//                $data = array('page_content' => 'daftar_user',
//                            'page_title' => 'registrasi',
//                            'level_user' => $reg['level'],
//                            'daftar_user' => $this->magen->get_agen_admin(),
//                            'user' => $this->session->userdata('username'),
//                            'isLogin' => TRUE,
//                            'note'=>'');
            }
        } else {
            $user_id = $this->uri->segment(4);
            $query = $this->madmin->get_user(array('user_id'=>$user_id));
            $udata = $query->row();
            $data = array(
                'isUpdate'=>TRUE,
                'page_title' => 'error | update user',
                'page_content' => 'tambah_user',
                'nama_belakang' => $udata->nama_belakang,
                'nama_depan' => $udata->nama_depan, 'email' => $udata->email,'password'=> $udata->password,
                'username' => $udata->username, 'user_id'=>$udata->user_id,
                'isLogin' => $islogin, 'level_user' => $level,
                'user' => $user);
       
        }

        $this->load->view($this->_admin_view, $data);  //tampilkan datanya
    }

    function hapus_user($user_id = null){
        $user_id = $this->uri->segment(4);
        $current_user = $this->madmin->get_user_id(array('username'=>$this->session->userdata('username')));
        if($user_id == $current_user){
            redirect('admin/profil','location');
        }

        if(!is_null($user_id) AND $user_id != 0){
            $this->magen->hapus_user(array('user_id'=>$user_id));
        }
        redirect('admin/profil','location');
    }

    /**
     * fungsi untuk mengecek duplikasi username pada database
     * @param <type> $username
     * @return <type>
     */
    public function spare_username($username){
        $sql = "SELECT username
                FROM user
                WHERE username=?";
        $query = $this->db->query($sql, array($username));
        $this->valid->set_message('spare_username',"Nama $username sudah ada. Silakan isi dengan username yg lain");
        return ($query->num_rows()==0)? TRUE : FALSE;

    }

    function get($id=""){
        //cek session       
        $isLogin = $this->session->userdata('isLogin');
        $user = ''; $id='';
        if ($isLogin) {
            $user = $this->session->userdata('username');
            $id = $this->session->userdata('user_id');
        }

        $sql = "select * from user where user_id = ?";
        $query = $this->db->query($sql,$id);
        $user = $query->row();
        $data_output['user']['username'] = $user->username;
        $data_output['user']['id'] = $user->user_id;
        $data_output['user']['nama_depan'] = $user->nama_depan;

        return $data_output;
    }

    function avatar(){
         //cek session       
        $isLogin = $this->session->userdata('isLogin');
        $user = ''; $id='';
        if ($isLogin) {
            $user = $this->session->userdata('username');
            $id = $this->session->userdata('user_id');
        }

        $data = array(
            'output' => $this->get($id,$id),
            'page_title' => 'Ubah Avatar',
            'isLogin' => $isLogin, 'user' => $user, 'id' => $id,
            'page_content' => 'form_avatar');
       $this->load->view($this->_admin_view, $data);
    }

    function avatarMotor(){
         //cek session       
        $isLogin = $this->session->userdata('isLogin');
        $user = ''; $id='';
        if ($isLogin) {
            $user = $this->session->userdata('username');
            $id = $this->session->userdata('user_id');
        }

        $data = array(
            'output' => $this->get($id,$id),
            'page_title' => 'Ubah Avatar Motor',
            'isLogin' => $isLogin, 'user' => $user, 'id' => $id,
            'page_content' => 'form_avatar_motor');
       $this->load->view($this->_public_view, $data);
    }

    function changeAvatar(){
        $isLogin = $this->session->userdata('isLogin');
        $user = ''; $id='';
        if ($isLogin) {
            $user = $this->session->userdata('username');
            $id = $this->session->userdata('user_id');
        }

        $data_output['success'] = "false";
        $file = 'avatar';
        $userid = $this->input->post('userId');
        $config['upload_path'] = 'pictures/user/';
        $config['allowed_types'] = '*';
        $config['overwrite'] = TRUE;
        $config['file_name'] = $userid;
        $config['max_size'] = '2048';
        $this->load->library('upload', $config);
        if($this->upload->do_upload($file)) // if upload success
        {
            $result = $this->upload->data();
            foreach($result as $item => $value){
                $filename = $result['file_name'];
                $this->make_thumb($result['file_path'].$filename, $config['upload_path'].'thumb/'.$config['file_name'].'t'.$result['file_ext'], 150, 150);
            }
            $input_data = array(
                'url' =>  $config['file_name'].'t_thumb'.$result['file_ext'],
                'last_update_media' => date("Y-m-d H:i:s"),
            );
            $this->db->where('user_id', $userid);
            $this->db->update('media', $input_data);
            $data_output['success'] = "true";
            
        }
        else{
            $data_output['debugfile'] = $this->upload->do_upload($file);
            $data_output['debugid'] = $userid;
        }
        redirect('admin/dashboard'); 
         
        // header('Content-Type: application/json');
        // echo json_encode($data_output);
    }

    function changeAvatarMotor(){
        $isLogin = $this->session->userdata('isLogin');
        $user = ''; $id='';
        if ($isLogin) {
            $user = $this->session->userdata('username');
            $id = $this->session->userdata('user_id');
        }

        $data_output['success'] = "false";
        $file = 'avatarmotor';
        $userid = $this->input->post('userId');
        $config['upload_path'] = 'motor/';
        $config['allowed_types'] = '*';
        $config['overwrite'] = TRUE;
        $config['file_name'] = $userid;
        $config['max_size'] = '2048';
        $this->load->library('upload', $config);
        if($this->upload->do_upload($file)) // if upload success
        {
            $result = $this->upload->data();
            foreach($result as $item => $value){
                $filename = $result['file_name'];
                $this->make_thumb($result['file_path'].$filename, $config['upload_path'].'thumb/'.$config['file_name'].'t'.$result['file_ext'], 150, 150);
            }
            $input_data = array(
                'avatarMotor' => $config['file_name'].'t_thumb'.$result['file_ext'],
                'lastUpdatedAvatarMotor' => date("Y-m-d H:i:s"),
            );
            $this->db->where('idUser', $userid);
            $this->db->update('userprofile', $input_data);
            $data_output['success'] = "true";
        }
        // header('Content-Type: application/json');
        // echo json_encode($data_output);
        redirect('profil/detail/'.$id); 
    }
    
    function make_thumb($src, $dest, $desired_width, $desired_height) {
        $source_path = $src;
        $target_path = $dest; 
        $config['image_library'] = 'gd2';
        $config['source_image'] = $source_path;
        $config['new_image'] = $target_path;
        $config['create_thumb'] = TRUE;
        $config['maintain_ratio'] = FALSE;
        $config['width']     = $desired_width;
        $config['height']   = $desired_height;

        $this->load->library('image_lib', $config); 

        $this->image_lib->resize();

        /* read the source image */
        //$source_image = imagecreatefromjpeg($src);
        
        //$width = imagesx($source_image);
        //$height = imagesy($source_image);
        
        /* find the "desired height" of this thumbnail, relative to the desired width  */
        //$desired_height = floor($height * ($desired_width / $width));
        
        /* create a new, "virtual" image */
        //thumb($src, 't', $desired_width, $desired_height);
        //$virtual_image = imagecreatetruecolor($desired_width, $desired_height);
        
        /* copy source image at a resized size */
        //imagecopyresampled($virtual_image, $source_image, 0, 0, 0, 0, $desired_width, $desired_height, $width, $height);
        
        /* create the physical thumbnail image to its destination */
        //imagejpeg($virtual_image, $dest);
    }

}

?>
